import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, TableC } from '../../../../comps';
import { message, Modal } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './OrderFormC';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    isShow: false, //二次确认模态框显示隐藏
    querys: {}, //二次确认详情数据
    isCanOrder: true, //组合是否可以下达 默认可以
    trailColumns: [], //试算结果列表
    trailDataSource: [], //试算结果数据
    trailModel: false, //试算模态框
    productCode: undefined, //产品code
    portfolioCode: undefined, //组合code
    uid: '',
  };
  componentDidMount() {
    this.props.onRef(this);
    uniqueKey().then((r) => {
      this.setState({ uid: r });
    });
  }
  //用户点击下达或确定按钮
  onOk = () => {
    const { type, isStop } = this.props;
    // 在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.orderFormRef.getInfo();
    //校验页面数据
    if (!data) return;
    data.uid = this.state.uid;
    if (isStop == '停牌') {
      message.warning('该证券代码已经停牌，无法下达');
      return;
    }
    if (type == 1) {
      if (this.state.isShow) {
        this.confirmOk(data); //二次确认的确定 点击按钮
      } else {
        //指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      //簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
  };
  //用户点击取消
  onCancel = () => {
    this.orderFormRef.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };
  //指令下达
  confirmOk = (params) => {
    const {
      dispatch,
      type,
      user: { currentUser },
    } = this.props;
    if (type == 11) {
      // 组合试算-委外投资
      params = {
        portfolioCode: this.state.portfolioCode,
        productCode: this.state.productCode,
        type: '21',
        businessType: '21',
        userId: params.userid,
        userName: params.username,
        tenant: currentUser.tenant, //租户code
        uid: params.uid,
        trade21: {
          ...params,
        },
      };
    }
    if (type == 2) {
      //簿记下达
      params.method = '0';
    }
    let url = type == 1 ? 'OutSourcingOrderM/saveOrder' : type == 11 ? 'portfolioTrialAddM/zcglPlanSave' : 'OutSourcingOrderM/tradeBookSave';
    if (type == 2) {
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, url, params, dispatch, (msg) => {
          if (msg) {
            //簿记下达成功
            this.props.onOk();
            this.onCancel(); //初始化form表单
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        })
      )
        return;
    }
    // 指令下达
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (msg) => {
        if (msg) {
          if (type == 2) {
            //簿记下达成功
            this.props.onOk();
            this.onCancel(); //初始化form表单
          } else {
            //指令下达成功
            this.onCancel(); //初始化form表单
            this.handleCancel(); //关闭模态框
          }
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };
  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading, type } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 1200,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['OutSourcingOrderM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3.1'} info={querys} />
      </ModalC>
    );
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  //试算按钮点击
  trialOnClick = () => {
    const {
      type,
      user: { currentUser },
    } = this.props;
    if (!this.orderFormRef) {
      return;
    }
    const data = this.orderFormRef.getInfo();
    //校验页面数据
    if (!data) return;
    let obj = {};
    obj.productCode = this.state.productCode; //产品code
    obj.portfolioCode = this.state.portfolioCode; //组合code
    obj.tenant = currentUser.tenant; //租户code
    obj.businessType = '21';
    obj.type = '21';
    obj.trade21 = { ...data };
    this.setState({ trailModel: true }, () => {
      this.props.dispatch({
        type: 'trailM/trialData',
        payload: obj,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  //获取组合code
  portfolioCode = (e) => {
    this.setState({
      portfolioCode: e?.info?.portfolioCode,
    });
    this.props.portfolioOnChange(e?.key);
    //指令下达的时候进行校验组合是否配置
    if (this.props.type == 1) this.queryIsAccountConfigured(e);
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else {
      this.setState({ productCode: undefined });
    }
  };
  render() {
    const { loading, type } = this.props;
    return (
      <>
        <OrderFormC
          type={type}
          tradingcodeOnChange={this.props.tradingcodeOnChange}
          portfolioOnChange={this.portfolioCode}
          productOnChange={this.productCode}
          onRef={(ref) => (this.orderFormRef = ref)}
          money={this.props.money}
          investmentType={this.props.position.investmentType}
          position={this.props.position}
          dateInterval={this.props.dateInterval}
        />
        <div style={{ marginTop: '10px' }} className={style.btnOperate}>
          {/* {type == 2 && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "16px" }}
          />} */}
          <PrimaryC loading={loading.effects['OutSourcingOrderM/tradeBookSave'] === true} onClick={this.onOk} title={this.props.type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '16px' }} />
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
      </>
    );
  }
}
export default connect(({ userM: user, loading, trailM, isAccountConfiguredM }) => ({
  user,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(AddOrderC);
